package com.itheima.app.gateway.filter;

import com.itheima.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.function.Consumer;

@Slf4j
@Component
public class AuthorizeFilter implements Ordered , GlobalFilter {

    //全局过滤器
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //通过request对象获取请求地址
        String path = request.getURI().getPath();
        //判断请求的地址是否是登录,如果是则放行 如果路径包含
        if (path.contains("login_auth")){
            return chain.filter(exchange);
        }
        //如果不是则获取请求头里的token
        String token = request.getHeaders().getFirst("token");
        //判断token是否为空 如果为空则返回401
        if (StringUtils.isEmpty(token)) {
            //返回401状态
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //如果不为空则校验token的合法性和有效性 如果校验通过则放行 不通过返401
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //判断是否过期
            int result = AppJwtUtil.verifyToken(claimsBody);
            //判断请求状态是否过期
            if (result == 1 || result == 2) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                //结束请求
                return response.setComplete();
            }
            //通过token获取用户登录信息
            String id = claimsBody.get("id").toString();

            //对象request的请求头进行增强 --添加一个key-value键值对
            ServerHttpRequest serverHttpRequest = request.mutate().headers(new Consumer<HttpHeaders>() {
                @Override
                public void accept(HttpHeaders httpHeaders) {
                    httpHeaders.add("userId", id);
                }
            }).build();

            //然后替换老的request请求对象
            exchange.mutate().request(serverHttpRequest).build();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //放行
        return chain.filter(exchange);
    }

    //返回值是用来做过滤器排序的 值越小 优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
